package com.atom.module.author.service.impl;

import com.atom.module.author.context.PermissionContextHolder;
import com.atom.module.author.pojo.entity.Permission;
import com.atom.module.author.pojo.entity.Role;
import com.atom.module.author.security.LoginUser;
import com.atom.module.author.service.PermissionService;
import com.atom.module.author.utils.SecurityUtils;
import com.atom.module.common.constant.Constants;
import com.atom.module.common.utils.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.Collection;
import java.util.List;
import java.util.Objects;

@Service("ps")
public class PermissionServiceImpl implements PermissionService {

    /**
     * 验证用户是否具备某权限
     *
     * @param permission 权限字符串
     * @return 用户是否具备某权限
     */
    public boolean hasPermission(String permission) {
        if (StringUtils.isEmpty(permission)) {
            return false;
        }
        LoginUser loginUser = SecurityUtils.getLoginUser();
        if (StringUtils.isNull(loginUser) || CollectionUtils.isEmpty(loginUser.getPermissions())) {
            return false;
        }
        PermissionContextHolder.setContext(permission);
        return hasPermissions(loginUser.getPermissions(), permission);
    }

    /**
     * 验证用户是否不具备某权限，与 hasPermi逻辑相反
     *
     * @param permission 权限字符串
     * @return 用户是否不具备某权限
     */
    public boolean lacksPermission(String permission) {
        return !hasPermission(permission);
    }

    /**
     * 验证用户是否具有以下任意一个权限
     *
     * @param permissions 以 PERMISSION_DELIMETER 为分隔符的权限列表
     * @return 用户是否具有以下任意一个权限
     */
    public boolean hasAnyPermission(String[] permissions) {
        if (StringUtils.isEmpty(permissions)) {
            return false;
        }
        LoginUser loginUser = SecurityUtils.getLoginUser();
        if (StringUtils.isNull(loginUser) || CollectionUtils.isEmpty(loginUser.getPermissions())) {
            return false;
        }
        PermissionContextHolder.setContext(permissions);
        List<Permission> permissionsList = loginUser.getPermissions();
        for (String permission : permissions) {
            if (hasPermissions(permissionsList, permission)) {
                return true;
            }
        }
        return false;
    }

    /**
     * 判断是否包含权限
     *
     * @param permissions 权限列表
     * @param permission  权限字符串
     * @return 用户是否具备某权限
     */
    private boolean hasPermissions(List<Permission> permissions, String permission) {
        permission = StringUtils.trim(permission);
        for (Permission entity : permissions) {
            if (Constants.ALL_PERMISSION.equals(entity.getValue())) {
                return true;
            }
            if (Objects.equals(permission, entity.getValue())) {
                return true;
            }
        }
        return false;
    }
}
